import { createElement, useEffect, useRef, useState, useMemo, forwardRef } from 'react';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import { Button, Checkbox, Divider, Select, Popover, Form, Input, TreeSelect, message } from 'antd';
import { ReloadOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import moment from 'moment';
import { cloneDeep } from 'lodash';
import IconFont from '@/components/IconFont';
import { CanSelectedSection } from '@/views/components/CustomSmallWrapper';
import { QueryButton } from '@/pages/OrderModule/orderList/components/Filter/components/QuicklyQuery/queryButton.jsx';
import QuickSearchModal from '@/pages/OrderModule/orderList/components/Filter/OrderShipFilter/QuickSearchModal';
import { timeOutOptions, treeData1, dealTree1Select, treeData2, dealTree2Select, afterTypeOptions, interceptOptions } from './constant.js';
import { RenderOrderSn, RenderLogisticNo, RenderTime, RenderSnArr, RenderOutOrderSnArr, RenderEcStoreIdArr } from './RenderFormItem.jsx';
import { getQuickSearchList, addQuickSearchOp, delQuickSearchOp, updateSortOp } from '@/pages/OrderModule/common/hooks/useConfig/services';
import { getTimeoutCountOp, getStatisticsOp } from '../services';
import styles from './index.module.less';

const { Option } = Select;
const { SHOW_PARENT } = TreeSelect;



const SelectBtn = ({ isSelect, text, children, onClick, style = {}, hasPosition }) => {

  return (<div className={`${styles.selectBtnWrapper} ${isSelect ? styles.isSelect : ''}`} onClick={onClick} style={{ ...style }}>
    {text || children}
    {hasPosition && <div style={{ position: 'absolute', right: '0px', bottom: '-8px' }}>
      <IconFont type="icona-juxing11766" />
    </div>}
  </div>)
}

const initParams = {
  timeOutType: 1, 
  timeOutRange: 12,
  openFlag: false,
  refundSn: 'afterSaleSn',
  logisticNo: 'refundLogisticsNo',
  timeType: 'applyTime'
}

export default ({ formData, orderBy, onResize, handleSearch }) => {

  const [form] = Form.useForm();
  const [expand, setExpand] = useState(true);
  const [filter, setFilter] = useState([]);
  const [staticNumberObj, setStaticNumberObj] = useState({});

  const [items, setItems] = useState([]);
  const [visible, setVisible] = useState(false);
  const [quickSearchId, setQuickSearchId] = useState('');

  const stageParams = useRef({...initParams});
  const originFormData = useRef({});

  useEffect(()=>{
    handelGetConfigList();
    setTimeout(()=>{
      form.setFieldsValue({
        platRefundStateList: [0, 1, 2, 3, 6, 7, 8, 12, 15]
      })
    })
  }, [])

  useEffect(()=>{
    if(orderBy == 'processingTimeRemain'){
      const platRefundStateList = (form.getFieldValue('platRefundStateList') || []).filter(item=>[0, 1, 2, 3, 6, 7, 8, 12, 15].includes(item));
      form.setFieldsValue({ platRefundStateList })
      handleSearch({
        ...formData,
        platRefundStateList
      })
    }else{
      handleSearch({...formData});
    }
  }, [orderBy])

  useEffect(() => {
    getStatisticsFunc();
    if(formData?.orderSn?.length){
      form.setFieldValue('orderSn', formData?.orderSn?.join(','));
    }
  }, [formData])

  useEffect(() => {
    if(!stageParams.current.openFlag){
      onFinish(true);
    }
  }, [filter])

  useEffect(()=>{
		onResize();
	}, [expand])

  const getStatisticsFunc = async () => {
    const promiseArr = [getTimeoutCountOp({ timeRange: stageParams.current.timeOutRange }), getStatisticsOp()];
    Promise.all(promiseArr).then(res => {
      setStaticNumberObj({
        ...(res?.[0]?.data || {}),
        ...(res?.[1]?.data || {}),
      });
    })
  }

  const handelGetConfigList = async () => {
    const { data, success} = await getQuickSearchList({ page: 'afsale-order' });
    if(success){
      setItems(data)
    }
  }

  const handelDelete = async (configId) => {
    const { data, success} = await delQuickSearchOp({ configId });
    if(success){
      handelGetConfigList();
    }
  }
  
  //点击快捷查询
  const handleClickQuickSearch = (value) => {
    const { id, param = '' } = value, obj = JSON.parse(param), originFormData = obj.originFormData || {};
    stageParams.current = {
      ...initParams,
      ...(obj.stageParams || {})
    }
    form.resetFields();
    if(originFormData.time?.length){
      originFormData.time = [moment(originFormData.time[0]), moment(originFormData.time[1])];
    }
    // console.log(obj,'obj')
    form.setFieldsValue(originFormData);
    setQuickSearchId(id);
    onFinish();
  }

  const SortableItem = SortableElement(({ value }) => (
    <div style={{marginRight:6}} onClick={()=>handleClickQuickSearch(value)}>
    <QueryButton item={value} form={form} quickSearchId={quickSearchId} onClear={(val)=>handelDelete(val)} />
    </div>
  ));

  const SortableList = SortableContainer(({ items }) => {
    return (
      <div style={{ display: 'inline-flex', flexWrap: 'wrap' }}>
        {items.map((value, index) => (
          <SortableItem key={`item-${index}`} index={index} value={value} />
        ))}
      </div>
    );
  });
  
  const submitAfterSortEnd = async ({ oldIndex, newIndex }) => {
   
    if(oldIndex == newIndex) return;
    const newItems = [...items];
    const [removedItem] = newItems.splice(oldIndex, 1);
    newItems.splice(newIndex, 0, removedItem);
    setItems(newItems);
    const arr = newItems.map((item,sort)=>({
      sort,
      id: item.id,
    }))
    await updateSortOp(arr);
};

  const QuickSearchModalProps = {
    items,
    stageParams,
    originFormData,
    searchForm: formData,
    page: 'afsale-order',
    handleOk(){
      setVisible(false);
      handelGetConfigList();
    },
    handleCancel(){
      setVisible(false);
    }
  }

  //检测表单是否有值
  const checkHasValue = (obj) => {
    Object.keys(obj).some(item=>{
      const currentValue = obj[item];
      if(typeof currentValue == 'undefined'){
        delete obj[item];
      }else if(Array.isArray(currentValue) && !currentValue?.length){
        delete obj[item];
      }
    })
    return Boolean(Object.keys(obj)?.length)
  }

  //快捷查询保存
  const handleSaveQuickSearch = () => {
    if(items?.length >= 5){
      return message.warn("搜索条件保存5个配置，请删除后再尝试");
    }
    const value = form.getFieldsValue();
    originFormData.current = cloneDeep(value);
    if(filter?.length || checkHasValue(value)){
      setVisible('QuickSearchModal');
    }else{
      message.info("请先进行检索");
    }
    console.log(filter, value);
  }

  const onFinish = (bool) => {
    if(bool && quickSearchId){
      setQuickSearchId('');
    }
    const values = form.getFieldsValue();
    Object.keys(values).map(item => {
      if (typeof values[item] == 'undefined') {
        delete values[item];
      }
      // else if(Array.isArray(values[item]) && !values[item]?.length)  delete values[item];
    })
    const params = {};

    if(filter.includes('timeOut')){
      params.timeoutRang = stageParams.current.timeOutRange;
    }

    if(filter.includes('returnConfirm')){
      params.refundConfirm = 1;
    }

    //平台售后单状态
    const platRefundStateList = values.platRefundStateList;
    if(platRefundStateList?.length){
      params.platRefundStateList = dealTree1Select(platRefundStateList);
      delete values.platRefundStateList;
    }
    //货物状态
    const unpackState = values.unpackState;
    if(unpackState?.length){
      params.unpackState = dealTree2Select(unpackState);
      delete values.unpackState;
    }
    //售后单号
    const refundSn = values.refundSn;
    if(refundSn){
      params[stageParams.current.refundSn == 'afterSaleSn' ? 'afterSaleSn' : 'platRefundSn'] = refundSn?.split(',');
      delete values.refundSn;
    }
    //退货快递
    const logisticNo = values.logisticNo;
    if(logisticNo){
      params[stageParams.current.logisticNo == 'refundLogisticsNo' ? 'refundLogisticsNo' : 'reissueLogisticsNo'] = logisticNo?.split(',');
      delete values.logisticNo;
    }
    //batchprint
    ['orderSn', 'outOrderSn'].map(item=>{
      if(values[item]){
        params[item] = values[item]?.split(',');
        delete values[item];
      }
    })
    //时间
    if(values.time){
      params[stageParams.current.timeType + 'Start'] = moment(values.time[0]).valueOf();
      params[stageParams.current.timeType + 'End'] = moment(values.time[1]).valueOf();
      delete values.time;
    }
    const obj = values.ecStoreId?.[0];
    if(obj){
      params.ecStoreId = obj.id;
    }
    delete values.ecStoreId;

    console.log(params, values)
    handleSearch({
      ...params,
      ...values
    })
  }

  const onReset = () => {
    stageParams.current = { ...initParams };
    form.resetFields();
    form.setFieldsValue({
      platRefundStateList: [0, 1, 2, 3, 15, 6, 7, 8, 12]
    })
    setFilter([]);
    riskChecked?.length && setRisk([]);
  }

  const tProps = {
    treeCheckable: true,
    maxTagCount: 'responsive',
    showCheckedStrategy: SHOW_PARENT,
    treeDefaultExpandAll: true
  }

  const [riskChecked, setRisk] = useState([]);

  useEffect(()=>{
    form.resetFields();
    if(riskChecked?.length){
      form.setFieldValue('unpackState', riskChecked);
      setFilter(['risk']);
    }else if(filter.includes('risk')){
      setFilter([]);
    }
  }, [riskChecked])

  const onOpenChange = (bool) => {
    stageParams.current.openFlag = bool;
    if(bool){
      stageParams.current.stageCheck = riskChecked;
    }else{
      const stageCheck = stageParams.current.stageCheck || [];
      if(stageCheck?.length != riskChecked?.length || stageCheck[0] != riskChecked[0]){
        onFinish();
      }
    }
  }

  const popcontent = () => {
    return <Checkbox.Group value={riskChecked} onChange={e=>setRisk(e)} onClick={e=>e.stopPropagation()}>
      <div><Checkbox value='defective'>卖家已收货_存在次品</Checkbox></div>
      <div><Checkbox value='less'>卖家已收货_部分收货</Checkbox></div>
    </Checkbox.Group>
  }

  const changeSelectAction = (type, value) => {
    stageParams.current = {
      ...stageParams.current,
      [type]: value
    }
    form.setFieldsValue({
      'platRefundStateList': value ? [0, 12] : [0, 1, 2, 3, 12],
      'afterTypeList': value ? [1, 2] : [0],
    })
    setFilter(['timeOut']);
  }

  const handleChangeFilter = (type) => {
    const isCancel = type == filter[0];

    let params = {};
    switch (type) {
      case 'timeOut':
        if (isCancel) {
          params.afterTypeList = [];
        } else {
          params.afterTypeList = stageParams.current.timeOutType ? [0, 1, 2] : [0];
        }
        break;
      case 'risk':
        params.unpackState = isCancel ? undefined : [...riskChecked];
        break;
      case 'notShippedRefund'://未发货仅退款
        params.afterTypeList = isCancel ? undefined : [2];
        params.platRefundStateList = [0, 12];
        break;
      case 'shippedRefund'://已发货仅退款
        params.afterTypeList = isCancel ? undefined : [1];
        params.platRefundStateList = [0, 12];
        break;
      case 'returnRefund'://退货退款
        params.afterTypeList = isCancel ? undefined : [0];
        params.platRefundStateList = [0, 1, 2, 3, 12];
        break;
      case 'pendingReturn'://待买家退货
        params.platRefundStateList = isCancel ? undefined : [2];
        break;
      case 'pendingSend'://待卖家发货
        params.platRefundStateList = isCancel ? undefined : [6];
        break;
      case 'finished'://已完结
        params.platRefundStateList = isCancel ? undefined : ['last'];
        break;
      default:
        console.log('params = {}')
    }
    !isCancel && form.resetFields();
    form.setFieldsValue(params);
    setFilter(isCancel ? [] : [type]);
  }

  const handleClickFirstSelectAction = () => {
    const isCancel = filter[0] == 'timeOut';
    if(isCancel){
      setFilter([]);
    }else{
      form.resetFields();
      const isFirstOption = Boolean(stageParams.current.timeOutType);
      form.setFieldsValue({
        'platRefundStateList': isFirstOption ? [0, 12] : [0, 1, 2, 3, 12],
        'afterTypeList': isFirstOption ? [1, 2] : [0],
      })
      setFilter(['timeOut']);
    }
  }

  return (<div style={{marginBottom:"16px"}}>
    { visible == 'QuickSearchModal' && <QuickSearchModal {...QuickSearchModalProps}/>}
    {
      expand && (<>
         <div style={{ display: 'flex', marginBottom: "12px" }}>
          <CanSelectedSection onClick={handleClickFirstSelectAction} isSelect={filter.includes('timeOut')} hasPosition>
             <li>
             <Select bordered={false} defaultValue={1} showArrow={false} 
              dropdownMatchSelectWidth={160} onClick={e => e.stopPropagation()} onChange={e => changeSelectAction('timeOutType', e)}>
              <Option value={1}>退款<span className='common-color9'>即将超时({staticNumberObj.refundTimeout || 0})</span></Option>
              <Option value={0}>退货退款<span className='common-color9'>即将超时({staticNumberObj.returnRefundTimeout || 0})</span></Option>
            </Select>
             </li>
             <Divider type="vertical" />
             <li>
             <Select bordered={false} options={timeOutOptions} defaultValue={12} showArrow={false}
              dropdownMatchSelectWidth={140} onClick={e => e.stopPropagation()} onChange={e => changeSelectAction('timeOutRange', e)}></Select>
             </li>
          </CanSelectedSection>
      {/* <SelectBtn onClick={() => handleChangeFilter('timeOut')} isSelect={filter.includes('timeOut')} hasPosition>
        <div>
          <div style={{ display: "inline-block", flex: 1, marginRight: '8px' }}>
            <Select bordered={false} defaultValue={1} showArrow={false} style={{ width: '140px', textIndent: "3px" }}
              dropdownMatchSelectWidth={172} onClick={e => e.stopPropagation()} onChange={e => changeSelectAction('timeOutType', e)}>
              <Option value={1}>退款<span className='common-color9'>即将超时({staticNumberObj.refundTimeout || 0})</span></Option>
              <Option value={0}>退货退款<span className='common-color9'>即将超时({staticNumberObj.returnRefundTimeout || 0})</span></Option>
            </Select>
          </div>
          <div style={{ display: "inline-block", flex: 1, borderLeft: '1px solid #ddd' }}>
            <Select bordered={false} options={timeOutOptions} defaultValue={12} showArrow={false} style={{ width: '140px', textIndent: "3px" }}
              dropdownMatchSelectWidth={172} onClick={e => e.stopPropagation()} onChange={e => changeSelectAction('timeOutRange', e)}></Select>
          </div>
        </div>
      </SelectBtn> */}
      <SelectBtn isSelect={filter.includes('risk')} hasPosition>
        <Popover content={popcontent} placement='bottomLeft' onOpenChange={onOpenChange}>
           <span>风险<span className='common-color9'>售后单</span></span>
        </Popover>
      </SelectBtn>
    </div>
    <div style={{ display: 'flex', marginBottom: "12px" }}>
      <SelectBtn onClick={() => handleChangeFilter('notShippedRefund')} isSelect={filter.includes('notShippedRefund')}>
        <span className='common-color9'>未发货</span>仅退款({staticNumberObj.notShippedRefund || 0})
      </SelectBtn>
      <SelectBtn onClick={() => handleChangeFilter('shippedRefund')} isSelect={filter.includes('shippedRefund')}>
        <span className='common-color9'>已发货</span>仅退款({staticNumberObj.shippedRefund || 0})
      </SelectBtn>
      <SelectBtn onClick={() => handleChangeFilter('returnRefund')} isSelect={filter.includes('returnRefund')}>
        <span className='common-color9'>退货退款</span>({staticNumberObj.returnRefund || 0})
      </SelectBtn>
      <SelectBtn onClick={() => handleChangeFilter('pendingReturn')} isSelect={filter.includes('pendingReturn')}>
        待<span className='common-color9'>买家</span>退货({staticNumberObj.pendingReturn || 0})
      </SelectBtn>
      <SelectBtn onClick={() => handleChangeFilter('returnConfirm')} isSelect={filter.includes('returnConfirm')}>
        <span className='common-color9'>卖家</span>已收货({staticNumberObj.returnConfirm || 0})
      </SelectBtn>
      <SelectBtn onClick={() => handleChangeFilter('pendingSend')} isSelect={filter.includes('pendingSend')}>
        待<span className='common-color9'>卖家</span>发货({staticNumberObj.pendingSend || 0})
      </SelectBtn>
      <SelectBtn onClick={() => handleChangeFilter('finished')} isSelect={filter.includes('finished')}>
        已完结({staticNumberObj.finished || 0})
      </SelectBtn>
    </div>
    <Form
      form={form}
      name="basic"
      layout='inline'
      onFinish={()=>onFinish(true)}
      autoComplete="off"
			className="views-search-form"
      style={{padding:"0px"}}
    >

      <Form.Item name='platRefundStateList' style={{ width: '215px', marginBottom: '8px' }}>
        <TreeSelect {...tProps} treeData={treeData1} placeholder='平台售后单状态（多选）' />
      </Form.Item>

      <Form.Item name='afterTypeList' style={{ width: '215px', marginBottom: '8px' }}>
        <Select
          mode="multiple"
          maxTagCount='responsive'
          allowClear
          placeholder="售后类型选择(多选)"
          options={afterTypeOptions}
          clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
        />
      </Form.Item>

      <Form.Item name='unpackState' style={{ width: '215px', marginBottom: '8px' }}>
        <TreeSelect {...tProps}  treeData={treeData2} placeholder='货物状态（多选）'/>
      </Form.Item>

      <Form.Item name='refundSn' style={{ width: '215px', marginBottom: '8px' }}>
        {createElement(RenderOrderSn, { stageParams })}
      </Form.Item>

      <Form.Item name='logisticNo' style={{ width: '215px', marginBottom: '8px' }}>
        {createElement(RenderLogisticNo, { stageParams })}
      </Form.Item>

      <Form.Item name='orderSn' style={{ width: '215px', marginBottom: '8px' }}>
        {createElement(RenderSnArr, { stageParams })}
      </Form.Item>

      <Form.Item name='outOrderSn' style={{ width: '215px', marginBottom: '8px' }}>
        {createElement(RenderOutOrderSnArr, { stageParams })}
      </Form.Item>


      <Form.Item name='reason' style={{ width: '215px', marginBottom: '8px' }}>
        <Input placeholder='售后原因问题（手动输入模糊搜索）' />
      </Form.Item>

      <Form.Item name='autoInterceptStatus' style={{ width: '215px', marginBottom: '8px' }}>
        <Select
          allowClear
          placeholder="拦截状态"
          options={interceptOptions}
          clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
        />
      </Form.Item>

      <Form.Item name="time" style={{ width: '448px', marginBottom: '8px' }}>
        {createElement(RenderTime, { stageParams })}
      </Form.Item>

      <Form.Item name='reissueShipState' style={{ width: '215px', marginBottom: '8px' }}>
        <Select
          allowClear
          placeholder="售后发货状态"
          clearIcon={<IconFont type="iconguanbi2fill" style={{ fontSize: '14px' }} />}
        >
          <Option value={0}>无需发货</Option>
          <Option value={1}>待发货</Option>
          <Option value={2}>已发货</Option>
        </Select>
      </Form.Item>

      <Form.Item name='ecGoodsName' style={{ width: '215px', marginBottom: '8px' }}>
        <Input placeholder='平台商品名称' />
      </Form.Item>

      <Form.Item name='ecSkuCode' style={{ width: '215px', marginBottom: '8px' }}>
        <Input placeholder='平台商品编码' />
      </Form.Item>

      <Form.Item name='ecSpuCode' style={{ width: '215px', marginBottom: '8px' }}>
        <Input placeholder='平台款式编码' />
      </Form.Item>

      <Form.Item name='ecGoodsSpec' style={{ width: '215px', marginBottom: '8px' }}>
        <Input placeholder='平台颜色规格' />
      </Form.Item>

      <Form.Item name='buyerNickName' style={{ width: '215px', marginBottom: '8px' }}>
        <Input placeholder='买家昵称' />
      </Form.Item>

      <Form.Item name='ecStoreId' style={{ width: '215px', marginBottom: '8px' }}>
         {createElement(RenderEcStoreIdArr)}
      </Form.Item>
      
      <div>
        <Button onClick={handleSaveQuickSearch} style={{ marginRight: 8 }}>另存为快捷查询</Button>
        <SortableList
          axis="xy"
          items={items}
          onSortEnd={submitAfterSortEnd}
          hideSortableGhost={false}
          helperClass="row-dragging"
          style={{ marginRight: 8 }}
        />
        <Button
          type="primary"
          icon={<IconFont type="iconsousuo" style={{ fontSize: 14 }} />}
          htmlType="submit"
          style={{ marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={onReset} className="mb16 ml8" style={{ order: 181 }}><ReloadOutlined /> 重置</Button>
      </div>
      </Form>
      {/* <div className={styles.quickSearchBox}>
        <div className={styles.quickSearchLeft}>
            <span>我的查询：</span>
            <SortableList
              axis="xy"
              items={items}
              onSortEnd={submitAfterSortEnd}
              hideSortableGhost={false}
              helperClass="row-dragging"
            />
          </div>
          <div className={styles.quickSearchRight}>
          <Button onClick={handleSaveQuickSearch}>另存为快捷查询</Button>
          </div>
       </div> */}
      </>)
    }
    <div className="toggle-search-form" style={{marginBottom:'6px'}}>
      <div className="toggle-search-form-target" onClick={()=>setExpand(!expand)}>
        {expand ? (
          <>
            <IconFont type="iconz045" />
            <span>收起</span>
          </>
        ) : (
          <>
            <IconFont type="iconzhankai" />
            <span>展开</span>
          </>
        )}
      </div>
    </div>
  </div>)
}